package application

// 数图的客流系统，从库中读取

import (
	"FlowMaster/config"
	"fmt"
	"log"
	"os"
	"time"

	"gorm.io/driver/sqlserver"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

type MonitorHeartTemp struct {
	DStart    time.Time `gorm:"column:DStart"`
	NEnters   int       `gorm:"column:NEnters"`
	NExits    int       `gorm:"column:NExits"`
	NPassings int       `gorm:"column:NPassings"`
	NReturns  int       `gorm:"column:NReturns"`
	SDev      string    `gorm:"column:SDev"`
}

func PFlib() (int, int) {
	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
		logger.Config{
			SlowThreshold:             time.Second, // 慢SQL阈值
			LogLevel:                  logger.Info, // 日志级别
			IgnoreRecordNotFoundError: true,        // 忽略记录未找到错误
			Colorful:                  false,       // 禁用彩色打印
		},
	)
	// dsn := "sqlserver://username:password@host:port?database=PFlib&encrypt=disable"
	loadPFlib, err := config.LoadPFlib()
	if err != nil {
		loggerI.Errorf("LoadPFlib error: %v", err)
	}
	dsn := fmt.Sprintf("sqlserver://%s:%s@%s:%d?database=%s&encrypt=disable", loadPFlib.Username, loadPFlib.Password, loadPFlib.Host, loadPFlib.Port, loadPFlib.Database)
	fmt.Printf("dsn: %v", dsn)
	db, err := gorm.Open(sqlserver.Open(dsn), &gorm.Config{
		Logger: newLogger,
	})
	if err != nil {
		loggerI.Errorf("数据连接失败: %v", err)
		panic("failed to connect database")
	}

	// 获取当前时间
	now := time.Now()

	// 构建当天0点的时间
	midnight := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location())
	loggerI.Debugf("当前时间: %v", midnight)
	// 如果当前时间正好是0点，我们需要查询昨天的数据
	if now.Equal(midnight) {
		return 0, 0
	}

	// 使用GORM的聚合函数求和
	var totalEnters int
	var totalExits int
	var result struct {
		TotalEnters   int `gorm:"column:total_enters"`
		TotalExits    int `gorm:"column:total_exits"`
		TotalPassings int `gorm:"column:total_passings"`
		TotalReturns  int `gorm:"column:total_returns"`
	}

	db.Raw("SELECT SUM(nEnters) as total_enters, SUM(nExits) as total_exits,SUM(nPassings) as total_passings,SUM(nReturns) as  total_returns FROM MonitorHeart_temp WHERE DStart >= ? AND DStart < ?", midnight, midnight.Add(24*time.Hour)).
		Scan(&result)
	te := result.TotalEnters
	ts := result.TotalExits
	tp := result.TotalPassings
	tr := result.TotalReturns
	// 输出查询结果
	loggerI.Debug(fmt.Sprintf("Total NEnters for today until now: %d\n", te))
	loggerI.Debug(fmt.Sprintf("Total NExits for today until now: %d\n", ts))
	loggerI.Debug(fmt.Sprintf("Total TotalPassings for today until now: %d\n", tp))
	loggerI.Debug(fmt.Sprintf("Total TotalReturns for today until now: %d\n", tr))
	coefficitent, _ := config.LoadCoefficient()
	totalEnters = (te + tp + tr) * coefficitent.In
	totalExits = ts * coefficitent.Out
	return totalEnters, totalExits
}
